import math as Math
import random
import datetime
import numpy as np

double_0 = 9876.0;
double_1 = 54321.0;


# 得到一个随机数，来自标准正态分布
def Gaus():
    return Gaus(0.0, 1.0);


# 得到一个随机数，来自正态分布(高斯分布)
def Gaus(mean, sigma):

    num2 = Rndm();
    while (num2 == 0.0):
        num2 = Rndm();

    a = Rndm() * 6.283185;
    return (mean + ((sigma * Math.Sin(a)) * Math.Sqrt(-2.0 * Math.Log(num2))));


def Rndm():
    return random.random


def Generate_Random_Rebalance_List(datetime1, datetime2, symbols=[], rebalance_days=30, datetime_as_string=False):
    #
    # symbols = ["AU.SHF", "H11001.CSI", "000300.SH", "SPX.GI"]
    #
    rebalance_list = []
    current_date = datetime1
    while current_date <= datetime2:
        #
        rebalance = False
        #
        if current_date == datetime1:
            rebalance = True
        #
        rebalance_day = random.randint(1, rebalance_days)
        if rebalance_day == rebalance_days: # 平均20天,命中一次，进行一次调仓
            rebalance = True

        if rebalance:
            # print("Rebalance", current_date)
            total_weight = 0
            #
            weights = []
            for symbol in symbols:
                random_weight = random.random()
                total_weight += random_weight
                weights.append(random_weight)
            #
            weights = np.asarray(weights)
            weights = weights / total_weight
            #
            positions = []
            for i in range(len(symbols)):
                symbol = symbols[i]
                weight = weights[i]
                positions.append({"symbol": symbol, "weight": weight})
            #
            s_current_date = current_date
            if datetime_as_string:
                s_current_date = current_date.strftime('%Y-%m-%d')
            #
            rebalance = {"datetime": s_current_date, "positions": positions}
            rebalance_list.append(rebalance)
        current_date += datetime.timedelta(days=1)
    #
    return rebalance_list